import { useEffect, useRef, useMemo, useContext } from 'react';
import { Context } from './constant';

export interface ExecutorProps {
  name: string;
  hook(): unknown;
}

const Executor = (props: ExecutorProps) => {
  const { hook, name } = props;

  const store = useContext(Context);

  const dataLoading = useRef(false);

  let data: unknown;

  try {
    data = hook();
  } catch (error) {
    console.error(`Invoking '${name || 'unknown'}' model failed:`, error);
  }

  useMemo(() => {
    store.update(name, data);
  }, []);

  useEffect(() => {
    if (dataLoading.current) {
      store.update(name, data);
    } else {
      dataLoading.current = true;
    }
  });

  return null;
};

export default Executor;
